package com.akk.task;

import com.akk.module.avs.entity.AvsApplyCard;
import com.akk.module.avs.entity.AvsApplyLoan;
import com.akk.module.avs.entity.AvsIncreRecord;
import com.akk.module.avs.service.AvsApplyCardService;
import com.akk.module.avs.service.AvsApplyLoanService;
import com.akk.module.avs.service.AvsIncreReocrdService;
import com.akk.module.avs.service.AvsPayOrderService;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 定时任务
 *
 * @company www.lovekaka.com
 * @auther hainlc
 * @create 2017/05/02 13:29
 */
@Component("scheduledTasks")
public class ScheduledTasks {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private AvsIncreReocrdService recordService;

    @Autowired
    private AvsApplyLoanService applyLoanService;

    @Autowired
    private AvsApplyCardService applyCardService;

    @Value("${spring.mail.username}")
    private String from;

    @Value("${record.mail.to}")
    private String to;

    @Autowired
    private AvsPayOrderService orderService;


    // 删除未支付订单
    public void delOrder() {
        String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        date += " 00:00:00";
        try {
            Date endDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(endDate);
            calendar.add(Calendar.DAY_OF_MONTH, -7);
            orderService.deleteByDate(calendar.getTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }


    public void sendRecordMail() {
//        mailSender = new JavaMailSenderImpl();
        MimeMessage message = mailSender.createMimeMessage();
        String yesterday = yesterday();
        String today = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String subject = "爱卡卡" + yesterday + "到" + today + "信用卡/贷款增值记录统计";
        // 所有贷款产品
        List<AvsApplyLoan> loans = applyLoanService.queryByParams(new HashMap());
        // 所有信用卡产品
        List<AvsApplyCard> cards = applyCardService.queryAll();
        // 内容
        StringBuffer content = new StringBuffer();
        // css
        String css = "<style>table.hovertable {font-family: verdana,arial,sans-serif;font-size:11px;color:#333333;border-width: 1px;border-color: #999999;border-collapse: collapse;}table.hovertable th {background-color:#c3dde0;\tborder-width: 1px;padding: 8px;\tborder-style: solid;border-color: #a9c6c9;}table.hovertable tr {background-color:#d4e3e5;}table.hovertable td {border-width: 1px;padding: 8px;border-style: solid;border-color: #a9c6c9;}}</style>";
        content.append(css);
        // 查询贷款记录信息
        for (AvsApplyLoan loanEntity : loans) {
            StringBuffer table = new StringBuffer();
            table.append("<table class=\"hovertable\">");
            table.append("<caption>");
            table.append(yesterday + "到" + today + loanEntity.getLoanName() + "贷款申请记录");
            table.append("<caption>");
            table.append("<tr><th>用户名</th><th>手机号</th><th>增值类型</th><th>增值产品</th><th>使用时间</th></tr>");
            Map params = new HashMap();
            params.put("type", "loan");
            params.put("typeId", loanEntity.getLoanId());
            params.put("startDate", yesterday);
            params.put("endDate", today);
            List<AvsIncreRecord> recordEntities = recordService.queryByParams(params);
            for (AvsIncreRecord recordEntity : recordEntities) {
                table.append("<tr onmouseover=\"this.style.backgroundColor='#ffff66';\" onmouseout=\"this.style.backgroundColor='#d4e3e5';\">");
                table.append("<td>" + recordEntity.getRecordUsername() + "</td>");
                table.append("<td>" + recordEntity.getRecordPhone() + "</td>");
                table.append("<td>贷款申请</td>");
                table.append("<td>" + loanEntity.getLoanName() + "</td>");
                table.append("<td>" + recordEntity.getCreateTime().toString() + "</td>");
                table.append("</tr>");
            }
            table.append("</table>");
            table.append("<hr>");
            if (recordEntities.size() != 0)
                content.append(table.toString());
        }

        // 查询信用卡记录信息
        for (AvsApplyCard cardEntity : cards) {
            StringBuffer table = new StringBuffer();
            table.append("<table class=\"hovertable\">");
            table.append("<caption>");
            table.append(yesterday + "到" + today + cardEntity.getCardBankName() + "申请记录");
            table.append("<caption>");
            table.append("<tr><th>用户名</th><th>手机号</th><th>增值类型</th><th>增值产品</th><th>使用时间</th></tr>");
            Map params = new HashMap();
            params.put("type", "card");
            params.put("typeId", cardEntity.getCardId());
            params.put("startDate", yesterday);
            params.put("endDate", today);
            List<AvsIncreRecord> recordEntities = recordService.queryByParams(params);
            for (AvsIncreRecord recordEntity : recordEntities) {
                table.append("<tr onmouseover=\"this.style.backgroundColor='#ffff66';\" onmouseout=\"this.style.backgroundColor='#d4e3e5';\">");
                table.append("<td>" + recordEntity.getRecordUsername() + "</td>");
                table.append("<td>" + recordEntity.getRecordPhone() + "</td>");
                table.append("<td>信用卡申请</td>");
                table.append("<td>" + cardEntity.getCardBankName() + "</td>");
                table.append("<td>" + recordEntity.getCreateTime().toString() + "</td>");
                table.append("</tr>");
            }
            table.append("</table>");
            table.append("<hr>");
            if (recordEntities.size() != 0)
                content.append(table.toString());
        }
        try {
            String[] tos = to.split(",");
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(tos);
            helper.setSubject(subject);
            helper.setText(content.toString(), true);
            mailSender.send(message);
            logger.info("邮件已发送");
            System.out.println("发送成功>>>>>>>>>>>>>>>>>>>>>>.");
        } catch (MessagingException e) {
            e.printStackTrace();
            System.out.println("发送失败>>>>>>>>>>>>>>>>>>>>>>.");
            logger.error("邮件发送失败");
        }
    }


    @Test
    public void test() {
        List<Integer> dataList = new ArrayList<Integer>();
        for (int i = 0; i < 12888; i++)
            dataList.add(i);
        //分批处理
        if (null != dataList && dataList.size() > 0) {
            int pointsDataLimit = 1000;//限制条数
            Integer size = dataList.size();
            // 判断是否有必要分批
            if (pointsDataLimit < size) {
                int part = size / pointsDataLimit;//分批数
                System.out.println("共有 ： " + size + "条，！" + " 分为 ：" + part + "批");
                //
                for (int i = 0; i < part; i++) {
                    //1000条
                    List<Integer> listPage = dataList.subList(0, pointsDataLimit);
                    System.out.println(listPage);
                    //剔除
                    dataList.subList(0, pointsDataLimit).clear();
                }

                if (!dataList.isEmpty()) {
                    System.out.println(dataList);//表示最后剩下的数据
                }
            } else {
                System.out.println(dataList);
            }
        } else {
            System.out.println("没有数据!!!");
        }
    }

    private String yesterday() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -1);
        Date time = cal.getTime();
        return new SimpleDateFormat("yyyyMMdd").format(time);
    }

    private Date yesterdayDate() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -1);
        Date time = cal.getTime();
        return time;
    }


    @Test
    public void dateTest() {
        String yesterday = yesterday();
        String today = new SimpleDateFormat("yyyyMMdd").format(new Date());
        System.out.println(yesterday + "----------" + today);
        sendRecordMail();
    }

}


